﻿using SYH.Domain.Common;
using SYH.Domain.ViewModels.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Collections;
using Newtonsoft.Json;
using fmtx.Framework.DALFactory;
using SYH.IBLL;
using System.Globalization;
using SYH.Web.Models;

namespace SYH.Web.Controllers.Common
{
    /// <summary>
    /// 上传文件的控制器
    /// 用于在有需要上传文件的组件中提供上传文件的 UI 和相应的一些简单处理
    /// </summary>
    public class UploadController : BaseController
    {
        private readonly static string writeLog = ConfigurationManager.AppSettings["writeLog"];
        private readonly IEntityRepository<BusinessFile> _FileService;

        public UploadController(
            IEntityRepository<BusinessFile> fService
        )
        {
            this._FileService = fService;
        }

        /// <summary>
        /// 这个用于范例说明
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// js上传文件
        /// </summary>
        /// <returns></returns>
        public  ActionResult QQUpLoadFile(string fileType, string relID)
        {
            var result = "";
            var fileRecord = new BusinessFile();
            var mainID = Guid.NewGuid();
            var filename = Request["qqfilename"];
            var gis = Request.Files["qqfile"];
            var saveFileSuffix = Path.GetExtension(filename).ToLower();
            var ext = saveFileSuffix.Substring(1, saveFileSuffix.Length-1);
            var newname = mainID.ToString().Replace("-","") + saveFileSuffix;
            var fileFolder = "";
            var downFolder = "";
            if (string.IsNullOrEmpty(relID))
            {
                relID = Guid.Empty.ToString();
            }

            if (ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "png")
            {
                if (gis.ContentLength > 900 * 1024)
                {
                    Response.StatusCode = 500;
                    result = JsonConvert.SerializeObject(new JsonUploadVM(false) { msg = "图片文件请上传小于900KB的文件!!" });
                    goto Finish;
                }
            }

            var savefile = true;//是否数据持久化
            switch (fileType)
            {
                case "commonFile": // 普通文件
                    mainID = fileRecord.ID;
                    fileFolder = ConfigurationManager.AppSettings["DefaultCommonFileUploadUrl"];
                    downFolder = ConfigurationManager.AppSettings["DefaultCommonFileUploadUrl"].ToString().Replace('\\', '/');
                    break;
                default:
                    mainID =Guid.Empty;
                    savefile = false;
                    fileFolder =ConfigurationManager.AppSettings["DefaultTempUploadUrl"];
                    downFolder = ConfigurationManager.AppSettings["DefaultTempUploadUrl"].ToString().Replace('\\', '/');
                    break;
            }
            if (gis != null && filename != null)
            {
                try
                {
                    var filePath = Server.MapPath(fileFolder+ext+"/");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    try
                    {
                        gis.SaveAs(filePath+ newname);
                        #region 持久化关系处理
                        if (savefile)
                        {
                            var localFileName = newname;
                            var saveFileName = Path.GetFileName(filename).ToLower();
                            var iconString = _GetFileIconString(saveFileSuffix);
                            fileRecord.Name = saveFileName;
                            fileRecord.UploadPath = downFolder + ext + "/";
                            fileRecord.Description = "普通文件";
                            fileRecord.OriginalFileName = localFileName;
                            fileRecord.UploadFileSuffix = saveFileSuffix;
                            fileRecord.DownLoaddPath = downFolder + ext + "/" + localFileName;
                            fileRecord.AttachmentTimeUploaded = DateTime.Now;
                            fileRecord.FileSize = gis.ContentLength;
                            fileRecord.RelevanceObjectID = Guid.Parse(relID);
                            fileRecord.IconString = iconString;//字符串长度不够
                            _FileService.SaveBo(fileRecord);

                        }
                        #endregion
                        result = JsonConvert.SerializeObject(new JsonUploadVM() { success = true, file = downFolder + ext + "/" + newname, fileName = filename, id = mainID.ToString(), uploadPath = ConfigurationManager.AppSettings["DefaultBaseFolder"] });
                        goto Finish;
                    }
                    catch (Exception e)
                    {
                        Response.StatusCode = 500;
                        result = JsonConvert.SerializeObject(new JsonUploadVM(false) { msg = e.Message });
                        goto Finish;
                    }
                }
                catch (Exception ex)
                {
                    Response.StatusCode = 500;
                    result = JsonConvert.SerializeObject(new JsonUploadVM(false) { msg = ex.Message });
                    goto Finish;
                }

            }
            else {
                Response.StatusCode = 500;
                result = JsonConvert.SerializeObject(new JsonUploadVM(false) { msg="文件上传错误！！请查看是否有其他程序占用！！"});
                goto Finish;
            }
            Finish:
            Response.Write(result);
            Response.End();
            return null;
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="name"></param>
        /// <param name="fpath"></param>
        /// <returns></returns>
        public ActionResult Remove(Guid id)
        {
            if (id!=Guid.Empty)
            {
                PublicCs.Delete(id);
            }
            return Success();
        }
        
        /// <summary>
        /// 根据文件的后缀，生成显示用的象形符号
        /// </summary>
        /// <param name="fileSuffix"></param>
        /// <returns></returns>
        private string _GetFileIconString(string fileSuffix)
        {
            var iconString = "";
            switch (fileSuffix)
            {
                case ".doc":
                    iconString = "<span class='mif-file-word'></span>";
                    break;
                case ".docx":
                    iconString = "<span class='mif-file-word'></span>";
                    break;
                case ".ppt":
                    iconString = "<span class='mif-file-powerpoint'></span>";
                    break;
                case ".pptx":
                    iconString = "<span class='mif-file-powerpoint'></span>";
                    break;
                case ".xls":
                    iconString = "<span class='mif-file-excel'></span>";
                    break;
                case ".xlsx":
                    iconString = "<span class='mif-file-excel'></span>";
                    break;
                case ".pdf":
                    iconString = "<span class='mif-file-pdf'></span>";
                    break;
                case ".mp4":
                    iconString = "<span class='mif-file-film'></span>";
                    break;
                default:
                    iconString = "<span class='mif-attachment'></span>";
                    break;
            }
            return iconString;
        }

        /// <summary>
        /// KindEditor上传组件
        /// </summary>
        /// <returns></returns>
        public ActionResult KindUpload()
        {
            String aspxUrl = Request.Path.Substring(0, Request.Path.LastIndexOf("/") + 1);

            //文件保存目录路径
            String savePath = ConfigurationManager.AppSettings["DefaultArticleAttachmentUploadUrl"];

            //文件保存目录URL
            String saveUrl = ConfigurationManager.AppSettings["DefaultArticleAttachmentUploadUrl"];

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //最大文件大小
            int maxSize = 1024 * 1024 * 5;

            var imgFile = Request.Files["imgFile"];
            if (imgFile == null)
            {
                return showError("请选择文件。");
            }

            String dirPath = Server.MapPath(savePath);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
                //showError("上传目录不存在。");
            }

            String dirName = Request.QueryString["dir"];
            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }
            if (!extTable.ContainsKey(dirName))
            {
                return showError("目录名不正确。");
            }

            String fileName = imgFile.FileName;
            String fileExt = Path.GetExtension(fileName).ToLower();

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return showError("上传文件大小超过限制。");
            }

            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
            }

            //创建文件夹
            dirPath += dirName + "/";
            saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            String filePath = dirPath + newFileName;

            imgFile.SaveAs(filePath);

            String fileUrl = saveUrl + newFileName;

            Hashtable hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;
            return Json(hash, "text/html;charset=UTF-8", JsonRequestBehavior.AllowGet);
        }

        private JsonResult showError(string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            return Json(hash, "text/html;charset=UTF-8", JsonRequestBehavior.AllowGet);
        }
    }
}